package org.example.controller;

import com.sun.jna.Memory;
import com.sun.jna.ptr.IntByReference;
import org.example.Interface.HCNetSDK;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
public class CameraController {
    @Resource
    HCNetSDK hCNetSDK;

    int lUserID = -1;

    int lDChannel = -1;

    static final int maxPicSize = 1024 * 1024;

    @GetMapping("/image")
    public void getImage(HttpServletResponse response) throws IOException {
        // 登录
        login_V40("10.254.12.24",(short) 8000,"admin","Physics@whu");
        getDVRPic();
//        // 抓图存到缓冲区
//        HCNetSDK.NET_DVR_JPEGPARA jpegpara = new HCNetSDK.NET_DVR_JPEGPARA();
//        jpegpara.wPicQuality = 0;
//        jpegpara.wPicSize = 0;
//        Memory buffer = new Memory(maxPicSize);
//        IntByReference intByReference = new IntByReference(); // 返回图片数据大小
//        hCNetSDK.NET_DVR_CaptureJPEGPicture_NEW(lUserID, 1, jpegpara, buffer.getPointer(0), maxPicSize,intByReference);
//        byte[] imgbytes = new byte[intByReference.getValue()];
//        buffer.read(0, imgbytes, 0, imgbytes.length);
//        buffer.clear();
//        // 发送给请求方
//        ServletOutputStream outputStream = response.getOutputStream();
//        outputStream.write(imgbytes, 0, imgbytes.length);
//        outputStream.close();
        // 退出登录
        logout();
    }

    @GetMapping("/ctrl")
    public void ctrlPlatformMove(@RequestParam("dir") int dir, @RequestParam("stop") int stop) {
        login_V40("10.254.12.24",(short) 8000,"admin","Physics@whu");
        if (!hCNetSDK.NET_DVR_PTZControl_Other(lUserID, 1, dir, stop)) {
            System.out.println("cloud platform move fail, error code:" + hCNetSDK.NET_DVR_GetLastError());
        }
        logout();
    }
//    public void getImage(HttpServletResponse response) throws IOException {
//        // 获得待下载文件所在文件夹的绝对路径
//        // 获得文件输入流
//        FileInputStream inputStream = new FileInputStream(new File("C:\\Users\\IKun_DL\\Desktop\\tmp\\test.jpg"));
//        // 设置响应头、以附件形式打开文件
//        response.setHeader("content-disposition", "attachment; fileName=test.jpg" );
//        ServletOutputStream outputStream = response.getOutputStream();
//        int len = 0;
//        byte[] data = new byte[maxPicSize];
//        while ((len = inputStream.read(data)) != -1) {
//            outputStream.write(data, 0, len);
//        }
//
//        outputStream.close();
//        inputStream.close();
//    }

    private void logout() {
        // 退出程序时调用，每一台设备分别注销
        if (hCNetSDK.NET_DVR_Logout(lUserID)) {
            System.out.println("注销成功");
        }
        // SDK反初始化，释放资源，只需要退出时调用一次
        hCNetSDK.NET_DVR_Cleanup();
    }
    private void login_V40(String ip, short port, String user, String psw) {
        hCNetSDK.NET_DVR_Init();
        //注册
        HCNetSDK.NET_DVR_USER_LOGIN_INFO m_strLoginInfo = new HCNetSDK.NET_DVR_USER_LOGIN_INFO();//设备登录信息
        HCNetSDK.NET_DVR_DEVICEINFO_V40 m_strDeviceInfo = new HCNetSDK.NET_DVR_DEVICEINFO_V40();//设备信息

        m_strLoginInfo.sDeviceAddress = new byte[HCNetSDK.NET_DVR_DEV_ADDRESS_MAX_LEN];
        System.arraycopy(ip.getBytes(), 0, m_strLoginInfo.sDeviceAddress, 0, ip.length());

        m_strLoginInfo.sUserName = new byte[HCNetSDK.NET_DVR_LOGIN_USERNAME_MAX_LEN];
        System.arraycopy(user.getBytes(), 0, m_strLoginInfo.sUserName, 0, user.length());

        m_strLoginInfo.sPassword = new byte[HCNetSDK.NET_DVR_LOGIN_PASSWD_MAX_LEN];
        System.arraycopy(psw.getBytes(), 0, m_strLoginInfo.sPassword, 0, psw.length());

        m_strLoginInfo.wPort = port;
        m_strLoginInfo.bUseAsynLogin = false; //是否异步登录：0- 否，1- 是
        m_strLoginInfo.byLoginMode=0;  //0- SDK私有协议，1- ISAPI协议
        m_strLoginInfo.write();

        lUserID = hCNetSDK.NET_DVR_Login_V40(m_strLoginInfo, m_strDeviceInfo);
        if (lUserID == -1) {
            System.out.println("登录失败，错误码为" + hCNetSDK.NET_DVR_GetLastError());
            return;
        } else {
            System.out.println(ip + ":设备登录成功！");
            //相机一般只有一个通道号，热成像相机有2个通道号，通道号为1或1,2
            //byStartDChan为IP通道起始通道号, 预览回放NVR的IP通道时需要根据起始通道号进行取值
            // 官方demo原代码这if恒为false，前后矛盾
//            if ((int)m_strDeviceInfo.struDeviceV30.byStartDChan == 1 && (int)m_strDeviceInfo.struDeviceV30.byStartDChan == 33)
            if ((int)m_strDeviceInfo.struDeviceV30.byStartDChan == 1 || (int)m_strDeviceInfo.struDeviceV30.byStartDChan == 33) {
                //byStartDChan为IP通道起始通道号, 预览回放NVR的IP通道时需要根据起始通道号进行取值,NVR起始通道号一般是33或者1开始
                lDChannel = (int)m_strDeviceInfo.struDeviceV30.byStartDChan;
                System.out.println("预览起始通道号："+lDChannel);
            }
        }
    }


    //抓拍图片
    public void getDVRPic() throws IOException {

        //图片质量
        HCNetSDK.NET_DVR_JPEGPARA jpeg = new HCNetSDK.NET_DVR_JPEGPARA();
        // 设置图片的分辨率
        jpeg.wPicSize = 2;
        // 设置图片质量
        jpeg.wPicQuality = 2;

        IntByReference intByReference = new IntByReference();
        // 抓图到内存，单帧数据捕获并保存成JPEG存放在指定的内存空间中
        //需要加入通道
        ByteBuffer jpegBuffer = ByteBuffer.allocate(1024 * 1024);
        boolean is = hCNetSDK.NET_DVR_CaptureJPEGPicture_NEW(lUserID, 1, jpeg,
                jpegBuffer, 1024 * 1024, intByReference);

        // 抓图到文件
        //boolean is = sdk.NET_DVR_CaptureJPEGPicture(cameraInfo.UserId,cameraInfo.Channel,jpeg, fileNameString);
        if (is) {
            System.out.println("抓取成功,返回长度：" + intByReference.getValue());
        } else {
            System.out.println("抓取失败："+hCNetSDK.NET_DVR_GetLastError());
        }

    }
}
